package com.qigao.mall.web.controller.app.merchant;

import com.alibaba.fastjson.JSONObject;
import com.qigao.mall.api.DataStoreService;
import com.qigao.mall.api.LoginInfoService;
import com.qigao.mall.commons.dto.WeiChatLoginResultDto;
import com.qigao.mall.commons.dto.WeichatLoginDto;
import com.qigao.mall.commons.dto.WeichatTokenDto;
import com.qigao.mall.commons.enums.LoginTypeEnum;
import com.qigao.mall.commons.enums.Result;
import com.qigao.mall.commons.enums.ResultCode;
import com.qigao.mall.commons.po.UserInfo;
import com.qigao.mall.commons.utils.IDUtils;
import com.qigao.mall.web.config.QiGaoProperties;
import com.qigao.mall.web.constants.SsoConstant;
import com.qigao.mall.web.vo.admin.LoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author luiz
 * @Title:com.qigao.mall.web.controller.app
 * @ProjectName three-mall
 * @Description: 商户端登录相关API
 * @date 2019-10-25  16:56
 */
@RestController
@RequestMapping("/app/merchant/login")
@Api(tags = "商户端登录相关API",value = "商户端登录相关API")
public class MerchantLoginController {
    private static Logger logger= LoggerFactory.getLogger(MerchantLoginController.class);
    @Resource
    LoginInfoService loginInfoService;
    @Resource
    DataStoreService dataStoreService;
    @Resource
    QiGaoProperties qiGaoProperties;

    @RequestMapping(value = "/weichat/preLogin",method= {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "微信小程序预登录", notes = "微信小程序预登录")
    public Result<WeiChatLoginResultDto> doLogin(@RequestParam("weichatCode")String weichatCode){
        try{
            WeichatLoginDto weichatLoginDto=new WeichatLoginDto();
             String sysMerNo=qiGaoProperties.getSysMerNo();
            weichatLoginDto.setMerNo(sysMerNo);
            weichatLoginDto.setWeichatCode(weichatCode);
            return loginInfoService.weichatLogin(weichatLoginDto);
        }catch (Exception e){
            logger.error("[微信预登录]发生异常:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }

    @GetMapping("/weichat/checkToken")
    @ApiOperation(value = "微信小程序校验token", notes = "微信小程序校验token")
    public Result<String> checkToken(HttpServletRequest request){
        try{
            String authTokenId = request.getHeader(SsoConstant.SSO_TOKENID);
            String  sysUserStr=dataStoreService.getVal(authTokenId);
            UserInfo sysUser=JSONObject.parseObject(sysUserStr,UserInfo.class);
            if(StringUtils.isNotEmpty(sysUser.getResv1())){
                logger.warn("[微信TOKEN校验]token已存在，并且尚未失效，直接返回{}",authTokenId);
                return Result.newSuccess(authTokenId);
            }
            WeichatTokenDto weichatTokenDto=new WeichatTokenDto();
            String  merNo=qiGaoProperties.getSysMerNo();
            weichatTokenDto.setMerNo(merNo);
            weichatTokenDto.setAuthTokenId(authTokenId);
            return loginInfoService.checkToken(weichatTokenDto);
        }catch (Exception e){
            logger.error("[微信预登录]发生异常:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }


    /**
     * Login
     *
     * @return
     */
    @PostMapping("/doLogin")
    @ResponseBody
    @ApiOperation(value = "登录接口", notes = "登录接口")
    public Result<String> login(@RequestBody LoginVo loginVo) {
        String loginNo = loginVo.getLoginNo();
        if (StringUtils.isBlank(loginNo)) {
            return Result.newError(ResultCode.COMMON_PARAM_INVALID.getCode(), "登录号不能为空");
        }
        String loginPass = loginVo.getLoginPass();
        if (StringUtils.isBlank(loginPass)) {
            return Result.newError(ResultCode.COMMON_PARAM_INVALID.getCode(), "密码不能为空");
        }
        try {
            Result result = loginInfoService.doLogin(loginNo, loginPass);
            if (!result.isSuccess()) {
                return result;
            }
            UserInfo userInfo = (UserInfo) result.getData();
            String tokenId = IDUtils.genIdStr(LoginTypeEnum.ADMIN_TOKEN.getCode());
            dataStoreService.put(tokenId, JSONObject.toJSONString(userInfo),null);
            return Result.newSuccess(tokenId);
        } catch (Exception e) {
            logger.error("登录发生异常:{}", e);
            return Result.newError(ResultCode.FAIL);
        }
    }

    /**
     * Logout
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    @ResponseBody
    @ApiOperation(value = "登出接口", notes = "登出接口")
    public Result<String> logout(HttpServletRequest request) {
        String tokenId = request.getHeader(SsoConstant.SSO_TOKENID);
        if (StringUtils.isBlank(tokenId)) {
            return Result.newError(ResultCode.COMMON_PARAM_INVALID.getCode(), "tokenId 不能为空.");
        }
        // logout
        dataStoreService.del(tokenId);
        return Result.newSuccess();
    }

}
